package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.domain.Login;
import cn.itsource.ymcc.dto.LoginDto;
import cn.itsource.ymcc.exception.GlobalException;
import cn.itsource.ymcc.mapper.LoginMapper;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.ILoginService;
import cn.itsource.ymcc.util.AssertUtil;
import cn.itsource.ymcc.util.jwt.JwtUtils;
import cn.itsource.ymcc.util.jwt.PayloadData;
import cn.itsource.ymcc.util.jwt.RsaUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author cff
 * @since 2024-06-06
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {

    @Override
    public JsonResult login(LoginDto loginDto) {

        //根据username和type查询login表数据
        Login login = super.getOne(new LambdaQueryWrapper<Login>()
                .eq(Login::getUsername, loginDto.getUsername())
                .eq(Login::getType, loginDto.getType())
        );
        if (login == null) {
            throw new GlobalException("用户名或者密码不能为空");
        }
        //判断密码是否正确
        boolean matches = new BCryptPasswordEncoder().matches(loginDto.getPassword(),login.getPassword());
        AssertUtil.isTrue(matches, "密码错误");

        return JsonResult.success().setData(loginSuccess(login));
    }

    /**
     * 专门处理登录成功的业务
     * @param login
     * @return
     */
    private Map<String, String> loginSuccess(Login login) {
        Map<String, String> map = new HashMap<>();
        try {
            //1.用户类型为0的时候（后台管理系统用户），连表查询当前登录用户拥有的权限和菜单  [今天先不做]
            //2.JWT工具类生成JWT字符串  私钥加密  公钥解密
            PrivateKey privateKey = RsaUtils
                    .getPrivateKey(FileCopyUtils
                            .copyToByteArray(this.getClass().getClassLoader().getResourceAsStream("hrm_auth_rsa")));
            //加密得到token
            PayloadData payloadData = new PayloadData();
            login.setPassword(null);    //置空密码，更安全
            payloadData.setLogin(login);
            String token = JwtUtils.generateTokenExpireInMinutes(payloadData, privateKey, 60*24*30);  //24小时过期

            //3.封装到HashMap
            map.put("token", token);
            map.put("currentUser", JSON.toJSONString(login));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
}
